package com.jmlee.service.impl;


import com.jmlee.cache.AdminCache;
import com.jmlee.enums.AdminStatus;
import com.jmlee.mapper.AdminMapper;
import com.jmlee.pojo.*;
import com.jmlee.service.AdminService;
import com.jmlee.util.UUIDUtil;
import org.apache.ibatis.session.RowBounds;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * @Description TODO
 * @Author jmLee
 * @Date 2021/3/1 23:35
 * @Version 1.0
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminCache adminCache;


    @Override
    public Map<String, Object> login(String username, String password, int expiredSeconds) {

        Map<String, Object> map = new HashMap<>();

        Admin admin = adminMapper.selectAdminByName(username);

        if (admin != null) {

            // 判断用户状态
            if (admin.getStatus().equals(AdminStatus.DISABLE.getCode())) {
                map.put("fail", "您已被禁用");
                return map;
            } else if (admin.getStatus().equals(AdminStatus.DELETE.getCode())) {
                map.put("fail", "您已被删除，请联系系统管理员");
                return map;
            } else if (!password.equals(admin.getPassword())) {
                map.put("fail", "密码错误");
                return map;
            }


            // 生成登录凭证
            LoginTicket loginTicket = new LoginTicket();
            loginTicket.setUserId(admin.getId());
            loginTicket.setTicket(UUIDUtil.generateUUID());
            loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));


            // 将后台用户信息保存到缓存中，这一步代码移到后面的拦截器进行处理
//            adminCache.setAdmin(umsAdmin);


            // 每次登录成功后都要将用户Token放到缓存中，并返回给前端存储
            adminCache.setLoginTicket(loginTicket, expiredSeconds);

            map.put("ticket", loginTicket.getTicket());

        } else {
            map.put("fail", "用户不存在");
            return map;
        }

        return map;
    }

    @Override
    public int selectAdminListCount(Admin admin) {
        return adminMapper.selectAdminListCount(admin);
    }

    @Override
    public List<Admin> selectAdminList(Admin admin, RowBounds rowBounds) {
        return adminMapper.selectAdminList(admin, rowBounds);
    }


    @Override
    public void logout(String ticket) {

        adminCache.delLoginTicket(ticket);
    }

    @Override
    public Integer addAdminImage(Admin admin) {
        return adminMapper.insertAdminImg(admin);
    }


    //============================================后台用户===================================================
    @Override
    public List<Admin> getUserInfoList(Admin admin) {
        List<Admin> userInfoList = adminMapper.findAll(admin);
        return userInfoList;
    }


//    @Override
//    public boolean addAdmin(Admin admin) {
//
//        return adminMapper.addAdmin(admin);
//    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Boolean addNewUserInfo(Admin admin) {

        try {
            //roleID=2商家
            if ("商家".equals(admin.getRolename())) {

                adminMapper.insertUserInfo(admin);

                AShop aShop = new AShop();
                aShop.setaId(admin.getId());

                adminMapper.insertShop(aShop);



                return true;
            }else {
                adminMapper.insertUserInfo(admin);

            }
        } catch (Exception e) {
            return false;
        }

        admin.setCreateTime(new Date());
        return false;
    }

    @Override
    public int insertShop(AShop aShop) {
        return adminMapper.insertShop(aShop);
    }


    @Override
    public boolean delete(Admin admin) {
        int mark = adminMapper.deleteUser(admin);
        return mark > 0;
    }

    @Override
    public Integer updateAdminSubmit(Admin admin) {
        return adminMapper.updateAdminSubmit(admin);
    }

    @Override
    public Admin queryAdminById(Long id) {
        return adminMapper.queryAdminById(id);
    }

    @Override
    public Admin checkName(String username) {
        return adminMapper.checkName(username);
    }


    @Override
    public LoginTicket findLoginTicket(String ticket) {

        return (LoginTicket) adminCache.getLoginTicket(ticket);
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public Admin findAdminById(Long userId) {
        // 先去缓存中查找
        Admin admin = getCache(userId);

        if (admin == null) {
            admin = initCache(userId);
        }
        return admin;
    }

    // 1.优先从缓存中获取用户数据
    private Admin getCache(Long userId) {
        return adminCache.getAdmin(userId);
    }

    // 2.在缓存中取不到用户数据时则初始化用户缓存数据
    private Admin initCache(Long userId) {
        // 去数据库中查找用户
        Admin admin = adminMapper.selectAdminById(userId);
        // 保存到缓存中
        adminCache.setAdmin(admin);
        return admin;
    }

    // 3.当用户数据发生变更时直接清除缓存数据（这里不去修改缓存是为了保证并发访问安全,直接将缓存数据清除）
    private void clearCache(Long userId) {
        adminCache.delAdmin(userId);
    }

}
